package spring.boot.btc.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.boot.btc.common.BlockProperty;
import spring.boot.btc.model.Block;
import spring.boot.btc.model.Wallet;
import spring.boot.btc.service.MiningService;
import spring.boot.btc.utils.HashUtils;
import spring.boot.btc.utils.RsaUtils;

import java.util.List;

/**
 * 初始化创世区块已经在启动类中完成
 */
@Slf4j
@RestController
@RequestMapping("/block")
public class BlockController {

    @Autowired
    private MiningService miningService;


    @GetMapping("wallet")
    public String genWallet() {
        return Wallet.getInstance().getAddress();
    }


    @GetMapping("list")
    public List<Block> list() {
        return BlockProperty.blockList;
    }

    /**
     * 挖矿测试
     */
    @GetMapping("mining")
    public Object mining() {
        miningService.mining();
        return BlockProperty.blockList;
    }

    @GetMapping("mining/test")
    public Object miningTest() {
        miningService.mining();
        Block last = BlockProperty.getLast();
        String inputAddress = last.getTransaction().getTransactionInputList().get(0).getAddress();
        String outputAddress = last.getTransaction().getTransactionOutputList().get(0).getAddress();
        String myAddress = Wallet.getInstance().getAddress();
        String sysAddress = HashUtils.sha256(RsaUtils.getPublicKey(BlockProperty.sysSignKey));
        if (inputAddress.equals(sysAddress) && myAddress.equals(outputAddress)) {
            return BlockProperty.getLast().getHash();
        } else {
            return 0;
        }
    }

}
